package com.example.fenye.controller.forum;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.example.fenye.entity.forum.ForumUser;
import com.example.fenye.entity.forum.Topic;
import com.example.fenye.service.forum.TopicService;
import com.example.fenye.util.Page;
import com.example.fenye.util.R;

@Controller
@RequestMapping(value="/forum/topic")
public class TopicController {
	@Resource
	TopicService topicService;
	
	
	
	@GetMapping(value="/toPostTopic")
	public ModelAndView toPostTopic(){
		ModelAndView mav = new ModelAndView("forum/topic/toposttopic");
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value="/postTopic")
	public R postTopic(HttpServletRequest request, HttpSession session, String topicSubject, Long topicCategory){
		Topic topic = new Topic();
		topic.setTopicSubject(topicSubject);
		topic.setTopicCategory(topicCategory);
		topic.setTopicBy(((ForumUser)session.getAttribute("userLogin")).getUserId());
		topic.setTopicDate(new Date());
		
		Long topicId = topicService.addTopic(topic);
		if(topicId!=null){
			return R.ok();
		}else{
			return R.error();
		}
	}
	
	@RequestMapping(value="toTopicList")
	public String toTopicList(HttpServletRequest request){
		return "/forum/topic/topiclist";
	}
	
	
	@ResponseBody
	@RequestMapping(value="/topicList")
	public List<Topic> topicList(HttpServletRequest request, @RequestParam(name="pageNow",defaultValue="1") String pageNow){
		int pageNow_int =  Integer.parseInt(pageNow);
		
		//获取记录总数
	    int totalCount = topicService.getTopicsCount();
	    //page根据tatolCount和pageNow计算出需要的记录数在数据库中的位置范围
	    Page page = new Page(totalCount, Integer.parseInt(pageNow));
	    List<Topic> topicList = 
	        topicService.getTopicWrapper(page.getStartPos(), page.getPageSize());
	    //将数据返回给前端
	    return topicList;
	
	}
	
	@ResponseBody
	@RequestMapping(value="/topicTotalNum")
	public Page topicTotalNum(HttpServletRequest request){
		int totalNum = topicService.getTopicsCount();
		Page page = new Page();
		page.setTotalCount(totalNum);
		return page;
	}
	
}
